package com.alks.common.utils.excelUtils;

import org.jxls.area.Area;
import org.jxls.builder.AreaBuilder;
import org.jxls.common.CellRef;
import org.jxls.formula.FastFormulaProcessor;
import org.jxls.formula.FormulaProcessor;
import org.jxls.formula.StandardFormulaProcessor;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

public class CusJxlsHelper extends JxlsHelper
{
	private static Logger logger = LoggerFactory.getLogger(CusJxlsHelper.class);

	public static CusJxlsHelper instance()
	{
		return new CusJxlsHelper();
	}

	//重写了processTemplate这个方法
	@Override
	public void processTemplate(org.jxls.common.Context context, Transformer transformer) throws IOException
	{

		AreaBuilder areaBuilder = this.getAreaBuilder();
		boolean processFormulas = this.isProcessFormulas();

		areaBuilder.setTransformer(transformer);
		List<Area> xlsAreaList = areaBuilder.build();
		Iterator var4 = xlsAreaList.iterator();

		Area xlsArea;
		while (var4.hasNext())
		{
			xlsArea = (Area) var4.next();
			xlsArea.applyAt(new CellRef(xlsArea.getStartCellRef().getCellName()), context);
		}

		if (processFormulas)
		{
			var4 = xlsAreaList.iterator();

			while (var4.hasNext())
			{
				xlsArea = (Area) var4.next();
				this.setFormulaProcessor(xlsArea);
				xlsArea.processFormulas();
			}
		}
		//增加了删除template sheet的业务控制
		if (this.isDeleteTemplateSheet())
		{
			transformer.deleteSheet("TEMPLATE");
		}

		transformer.write();
	}

	//这里不想写的，但是不写会报错
	private Area setFormulaProcessor(Area xlsArea)
	{
		FormulaProcessor fp = this.getFormulaProcessor();
		if (fp == null)
		{
			if (this.isUseFastFormulaProcessor())
			{
				fp = new FastFormulaProcessor();
			} else
			{
				fp = new StandardFormulaProcessor();
			}
		}

		xlsArea.setFormulaProcessor(fp);
		return xlsArea;
	}

	@Override
	public Transformer createTransformer(InputStream templateStream, OutputStream targetStream)
	{

		PoiTransformer transformer = PoiTransformer.createTransformer(templateStream, targetStream);

//		if (super.expressionNotationBegin != null && expressionNotationEnd != null) {
//			transformer.getTransformationConfig().buildExpressionNotation(expressionNotationBegin,
//																		  expressionNotationEnd);
//		}
		transformer.setEvaluateFormulas(false);
		return transformer;

	}
}
